<?php
/**
  * wechat php test
  */

define("AUTHDOMAIN", "billeen.net");

class WechatCmd
{
	private $appid = 'wx5f071f58065f81ce';
	private $secret = '3f52f38dae2e4ff806634745170e9e5e';
	private function get_url_contents($url){
        $ch = curl_init();
        $timeout = 30;
        curl_setopt ($ch, CURLOPT_REFERER, "billyn.net");		
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $ret = curl_exec($ch);
        curl_close($ch);		
        return $ret;
	}
	
	private function post_url_contents($url, $data) {
		$ch = curl_init();
		$timeout = 30;
        curl_setopt ($ch, CURLOPT_REFERER, "billyn.net");		
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		'Content-Type: application/json',
		'Content-Length: ' . strlen($data))
		);
		$ret = curl_exec($ch);
		curl_close($ch);
		return $ret;
	}
	public function redirect() {
		if (isset($_GET['to'])) {
			$to = $_GET['to'];
		}
		if (isset($_GET['group'])) {
			$group = $_GET['group'];
		}
		header("Location:  https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->appid&redirect_uri=".urlencode("http://billyn.net/wechat/index.php?r=rediWithId&to=$to&group=$group")."&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
	}
	
	public function redirectReal() {
		if (!isset($_GET['code']) || !isset($_GET['to']) || !isset($_GET['state']) ) {
			return;
		}
		$code = $_GET['code'];
		$to = $_GET["to"];
		$state = $_GET["state"];
		$group = $_GET["group"];
		
		$str = $this->get_url_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appid&secret=$this->secret&code=$code&grant_type=authorization_code");
		$openid = json_decode($str)->openid;

		if (!strstr($to, '?', true)) {
			header('Location: ' . $to . '?openid=' . $openid . '&group=' . $group . '&guestSys=wechat') ;
		} else {
			header('Location: ' . $to . '&openid=' . $openid . '&group=' . $group . '&guestSys=wechat') ;
		}
		
	}
	
	private function getAccessToken() {
		$accTokenStr = $this->get_url_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->secret");
		return json_decode($accTokenStr)->access_token;
	}
	
	public function sendTextMsg($to, $msg)
	{
			$textTpl = '{
						"touser":"%s",
						"msgtype":"text",
						"text":
							{
							"content":"%s"
							}
						}';
			$msgType = "text";
			$data_string = sprintf($textTpl, $to, $msg); 
			$aToken = $this->getAccessToken();

			$this->post_url_contents("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$aToken",$data_string);
	}
}

?>